# import pygame
# import random
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 800
# SCREEN_HEIGHT = 600
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 加载背景图片
# background_image = pygame.image.load('back.png')
# background_image = pygame.transform.scale(background_image, (SCREEN_WIDTH, SCREEN_HEIGHT))
#
# # 颜色定义
# COLORS = [
#     (255, 0, 0),  # 红
#     (0, 255, 0),  # 绿
#     (0, 0, 255),  # 蓝
#     (255, 255, 0),  # 黄
#     (128, 0, 128)  # 紫
# ]
# BG_COLOR = (255, 255, 255)
# SLOT_COLOR = (200, 200, 200)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 60
# CARD_HEIGHT = 80
# SPACING = 10
#
# # 游戏区域布局
# GRID_ROWS = 3
# GRID_COLS = 3
# GRID_TOP = 100
#
# # 初始化卡片堆（每个位置3 - 4层）
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 4)
#         # 确保卡片类型数量为3的倍数
#         stack = [random.randint(0, len(COLORS) - 1) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
#
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 计算点击位置
#             grid_col = (x - SPACING) // (CARD_WIDTH + SPACING)
#             grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#             # 检查点击范围
#             if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                 if len(grid[grid_row][grid_col]) > 0:
#                     # 取出顶层卡片
#                     card = grid[grid_row][grid_col].pop()
#                     slots.append(card)
#                     # 检查连续三个
#                     if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                         del slots[-3:]
#                         score += 1
#                     # 检查失败条件
#                     if len(slots) > 7:
#                         game_over = True
#                     # 检查胜利条件
#                     if check_victory():
#                         game_won = True
#                         game_over = True
#
#     # 绘制界面
#     screen.blit(background_image, (0, 0))
#
#     # 绘制卡片堆
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = SPACING + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             if len(grid[row][col]) > 0:
#                 pygame.draw.rect(screen,
#                                  COLORS[grid[row][col][-1]],
#                                  (x, y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位
#     slot_y = SCREEN_HEIGHT - CARD_HEIGHT - 20
#     for i, card in enumerate(slots):
#         pygame.draw.rect(screen,
#                          COLORS[card],
#                          (20 + i * (CARD_WIDTH + 5), slot_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, (0, 0, 0))
#     screen.blit(text, (20, 20))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, (0, 255, 0) if game_won else (255, 0, 0))
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(30)
#
# pygame.quit()



import pygame
import random

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 加载背景图片
background_image = pygame.image.load('back.png')
background_image = pygame.transform.scale(background_image, (SCREEN_WIDTH, SCREEN_HEIGHT))

# 颜色定义
COLORS = [
    (255, 0, 0),  # 红
    (0, 255, 0),  # 绿
    (0, 0, 255),  # 蓝
    (255, 255, 0),  # 黄
    (128, 0, 128)  # 紫
]
BG_COLOR = (255, 255, 255)
SLOT_COLOR = (200, 200, 200)

# 卡片尺寸和间距
CARD_WIDTH = 60
CARD_HEIGHT = 80
SPACING = 10



# 存储卡片图片文件名的列表
card_image_files = ['tile1.png', 'tile2.png', 'tile7.png', 'tile12.png', 'tile11.png']
# 加载卡片图片
card_images = []
for file in card_image_files:
    try:
        image = pygame.image.load(file)
        image = pygame.transform.scale(image, (CARD_WIDTH, CARD_HEIGHT))
        card_images.append(image)
    except pygame.error as e:
        print(f"加载图片 {file} 时出错: {e}")

# 卡片尺寸和间距
CARD_WIDTH = 60
CARD_HEIGHT = 80
SPACING = 10

# 游戏区域布局
GRID_ROWS = 3
GRID_COLS = 3
# 计算卡片堆居中的起始位置
total_grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
total_grid_height = GRID_ROWS * (CARD_HEIGHT + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - total_grid_width) // 2
GRID_TOP = (SCREEN_HEIGHT - total_grid_height) // 2

# 初始化卡片堆（每个位置3 - 4层）
grid = []
for row in range(GRID_ROWS):
    grid_row = []
    for col in range(GRID_COLS):
        layers = random.randint(3, 4)
        # 确保卡片类型数量为3的倍数
        stack = [random.randint(0, len(card_images) - 1) for _ in range(layers)]
        stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
        grid_row.append(stack)
    grid.append(grid_row)

# 游戏状态
slots = []
score = 0
game_over = False
game_won = False


def check_victory():
    """检查是否胜利"""
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0


# 主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            x, y = pygame.mouse.get_pos()
            # 计算点击位置
            grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
            grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
            # 检查点击范围
            if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
                if len(grid[grid_row][grid_col]) > 0:
                    # 取出顶层卡片
                    card = grid[grid_row][grid_col].pop()
                    slots.append(card)
                    # 检查连续三个
                    if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                        del slots[-3:]
                        score += 1
                    # 检查失败条件
                    if len(slots) > 7:
                        game_over = True
                    # 检查胜利条件
                    if check_victory():
                        game_won = True
                        game_over = True

    # 绘制界面
    screen.blit(background_image, (0, 0))

    # 绘制卡片堆
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
            y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
            if len(grid[row][col]) > 0:
                screen.blit(card_images[grid[row][col][-1]], (x, y))

    # 绘制槽位
    slot_y = SCREEN_HEIGHT - CARD_HEIGHT - 20
    total_slot_width = len(slots) * (CARD_WIDTH + 5) - 5
    slot_left = (SCREEN_WIDTH - total_slot_width) // 2
    for i, card in enumerate(slots):
        screen.blit(card_images[card], (slot_left + i * (CARD_WIDTH + 5), slot_y))

    # 绘制状态信息
    font = pygame.font.Font(None, 36)
    text = font.render(f"Score: {score}", True, (0, 0, 0))
    screen.blit(text, (20, 20))

    if game_over:
        text = font.render("YOU WIN!" if game_won else "GAME OVER!",
                           True, (0, 255, 0) if game_won else (255, 0, 0))
        screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()


